package com.example.stock.controller;

import cn.hutool.core.date.DateUtil;
import com.example.stock.controller.dto.DailyDetailDTO;
import com.example.stock.mapper.DailyDetailMapper;
import com.example.stock.service.DailyDataService;
import com.example.stock.util.Result;
import com.example.stock.util.ResultGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin(origins = "*")
@RequestMapping("daily")
@RestController
public class DailyDateController {

    @Autowired
    DailyDataService dailyDataService;

    @GetMapping("{stock}")
    @Cacheable(value = "daily_detail", key = "#stock")
    public Result index(@PathVariable("stock") String stock) {
        List<DailyDetailDTO> dailyData = dailyDataService.getDailyData(stock);
        return ResultGenerator.genSuccessResult(dailyData);
    }

    @GetMapping("drawdown")
    public Result drawdown() {
        return ResultGenerator.genSuccessResult(
                dailyDataService.getDrawDownSatData()
        );
    }

    @GetMapping("week/{stock}/{date}")
    Result getByWeekDate(@PathVariable String stock, @PathVariable String date) {
        List<DailyDetailDTO> dailyData = dailyDataService.getDailyData(stock);

        String year =  date.substring(0, 4);
        String start =  date.substring(10, 14);
        String end =  date.substring(16, 20);

        String startDate = DateUtil.format(DateUtil.parse(year + start), "yyyy-MM-dd");
        String endDate = DateUtil.format(DateUtil.parse(year + end), "yyyy-MM-dd");


        return ResultGenerator.genSuccessResult(
                dailyData.stream()
                        .filter( i -> i.getDate().compareTo(startDate) >= 0)
                        .filter( i -> i.getDate().compareTo(endDate) < 0)
                        .toList()
        );
    }


    @Autowired
    DailyDetailMapper dailyDetailMapper;

    @GetMapping("consecutive/{stock}")
    @Cacheable(value = "consecutiveByStock", key = "#stock")
    public Result consecutiveByStock(@PathVariable String stock) {
        return ResultGenerator.genSuccessResult(dailyDetailMapper.getConsecutiveByStock(stock));
    }
}